//
//  AppDelegate.swift
//  WKweiBo
//
//  Created by 阿拉斯加的狗 on 15/12/6.
//  Copyright © 2015年 阿拉斯加的🐶. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        //设置颜色
        setUpAppearence()
        
        //创建窗口显示视图
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        window?.backgroundColor = UIColor.whiteColor()
        
        //设置根控制器
        window?.rootViewController = defaultRootViewController
        
        window?.makeKeyAndVisible()
        
        //监听通知
        NSNotificationCenter.defaultCenter().addObserverForName(WKSwitchRootViewControllerNotification, object: nil, queue: nil) {[weak self] (notification) -> Void in
            
            //控制器的判断
            let vc = notification.object != nil ? WelcomViewController() : WKMainController()
            
            //切换控制器
            self?.window?.rootViewController = vc
            
        }
    
        return true
    }

/// 程序进入后台时候消除缓存
    func applicationDidEnterBackground(application: UIApplication) {
        
        StatusDAL.clearDataCache()
    }
    
/// 销毁通知中心
    deinit{
    
        NSNotificationCenter.defaultCenter().removeObserver(self, name: WKSwitchRootViewControllerNotification, object: nil)
    }
    
    
    
    //设置外观对象设置统一的布局
    private func setUpAppearence(){
    
        //设置tabar的颜色
//        tabBar.tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = WKAppearanceTintColor
        
        //设置导航栏颜色
        UINavigationBar.appearance().tintColor = WKAppearanceTintColor
    
    
    }

}


/// 界面切换  
extension AppDelegate {

    //判断用户是否登录
    private var defaultRootViewController: UIViewController {
    
        if UserAccountViewModel.sharedUserAccount.userLogin{
        
            return isVewVersion ? NewFeatureViewController() : WelcomViewController()
            
        }
    
        //直接返回Main
        return WKMainController()
    
    }
    
/// 是否为新版本
        private var isVewVersion: Bool {
        
        //1.当前版本
            let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
            let version = Double(currentVersion)!
        
            //2.沙盒版本
            let sandboxVersionKey = "sandboxVersionKey"
            let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
            
            //3.保存到沙盒
            NSUserDefaults.standardUserDefaults().setDouble(version, forKey: sandboxVersionKey)
            
            //判断
            return version > sandboxVersion
            
        }
    
    }




